<template>
  <el-dialog
    :title="dialogObj.title"
    append-to-body
    :visible.sync="dialogObj.show"
    :close-on-click-modal="false"
    width="1200px"
  >
    <el-form
      ref="form"
      :model="form"
      label-width="120px"
      :rules="rules"
      :disabled="dialogObj.read"
      v-if="dialogObj.show"
      status-icon
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同编号：" prop="contractNumber">
            <el-input
              v-model="form.contractNumber"
              style="width:400px;"
              size="mini"
              maxlength="200"
              :disabled="dialogObj.id != ''"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同状态：" prop="status">
            <el-select
              v-model="form.status"
              placeholder="请选择"
              style="width:200px;"
              size="mini"
            >
              <el-option
                v-for="(data, index) in contractStatusList"
                :key="index"
                :label="data.value"
                :value="data.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户：" prop="customerId">
            <el-select
              v-model="form.customerId"
              placeholder="请选择"
              style="width:400px;"
              size="mini"
              filterable
              default-first-option
              @change="customerChanged"
              :disabled="dialogObj.id != ''"
            >
              <el-option
                v-for="(data, index) in customerList"
                :key="index"
                :label="data.customerName"
                :value="data.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人：" prop="customerContact">
            <el-input
              v-model="form.customerContact"
              style="width:400px;"
              size="mini"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="通信地址：" prop="customerAddress">
            <el-input
              v-model="form.customerAddress"
              style="width:400px;"
              size="mini"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电子邮箱：" prop="customerEmail">
            <el-input
              v-model="form.customerEmail"
              style="width:400px;"
              size="mini"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="移动电话：" prop="customerMobile">
            <el-input
              v-model="form.customerMobile"
              style="width:400px;"
              size="mini"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="行业类型：" prop="customerType">
            <el-input
              v-model="form.customerType"
              style="width:400px;"
              size="mini"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="乙方(受托人)：" prop="organizationId">
            <el-select
              v-model="form.organizationId"
              style="width:400px;"
              size="mini"
              @change="organizationChanged"
            >
              <el-option
                v-for="(data, index) in agentList"
                :key="index"
                :label="data.name"
                :value="data.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人(受托人)：" prop="trusteeContact">
            <el-input
              v-model="form.trusteeContact"
              style="width:400px;"
              size="mini"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="通信地址(受托人)：" prop="trusteeAddress">
            <el-input
              v-model="form.trusteeAddress"
              style="width:400px;"
              size="mini"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话号码(受托人)：" prop="trusteePhone">
            <el-input
              v-model="form.trusteePhone"
              style="width:400px;"
              size="mini"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="代理人：" prop="agentId">
            <el-select v-model="form.agentId" style="width:400px;" size="mini" >
              <el-option
                v-for="(data, index) in sysuserSelect"
                :key="index"
                :label="data.userName"
                :value="data.userId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="电子邮箱(受托人)：" prop="trusteeMail">
            <el-input
              v-model="form.trusteeMail"
              style="width:400px;"
              size="mini"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="移动电话(受托人)：" prop="trusteeMobile">
            <el-input
              v-model="form.trusteeMobile"
              style="width:400px;"
              size="mini"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="服务项目：" prop="serviceList">
        <files-list
          :tableData="tableData"
          @handleTableDate="handleTableDate"
          @handleChangeFee="handleChangeFee"
        >
        </files-list>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="总金额(元)：" prop="totalFee">
            <el-input
              v-model="form.totalFee"
              style="width:200px;marginRight:20px;"
              size="mini"
              maxlength="50"
              :disabled="true"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否到账：" prop="accountTransfer">
            <el-select
              v-model="form.accountTransfer"
              placeholder="请选择"
              style="width:200px;"
              size="mini"
              @change="transferChanged"
            >
              <el-option
                v-for="(data, index) in applyPayList"
                :key="index"
                :label="data.value"
                :value="data.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row>
        <el-col :span="12">
          <el-form-item label="合同文件：" prop="filePath">
            <upload-file
              :imageValue="form.filePath"
              :isNotlist="true"
              @handlefileSuccess="handlefileSuccess"
            >
            </upload-file>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="到账日期：" prop="transferDate">
            <el-date-picker
              v-model="form.transferDate"
              style="width:200px;"
              size="mini"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>


    </el-form>
    <span slot="footer" class="dialog-footer" v-if="!dialogObj.read">
      <el-button type="primary" @click="sub" size="mini">确 定</el-button>
      <el-button @click="dialogObj.show = false" size="mini">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
import filesList from "./filesList";
import uploadFile from "@c/uploadFile";
import { _debounce } from "@u/debounce";
import { validateEmpty } from "@u/validate";
import { CONTRACTSTATUSLIST, ISNOTLIST } from "@u/wordbook";
import {
  AddContractManageApi,
  updateContractManageApi,
  getCustomerListApi,
  getContractManageApi,
  getCustomerInfoApi,
  getAgentPageApi,
  getSysuserSelectApi,
} from "@s/api";
export default {
  name: "dialogCom",
  props: ["dialogObj"],
  components: {
    filesList,
    uploadFile,
  },
  data() {
    return {
      isUpdate: false,
      tableData: [],
      sysuserSelect: [], //代理人
      form: {
        id: "",
        customerId: "",
        organizationId: "", // 代理商
        agentId: "", // 代理人
        contractNumber: "",
        customerAddress: "",
        customerContact: "",
        customerEmail: "",
        customerMobile: "",
        customerType: "",
        trusteeAddress: "",
        trusteePhone: "",
        trusteeContact: "",
        trusteeMail: "",
        trusteeMobile: "",
        totalFee: "",
        payType: "",
        payNumber: "",
        filePath: "",
        status: "",
        accountTransfer: "",
        transferDate: "",
        projectInfos: [],
      },
      agentList: [],
      contractStatusList: CONTRACTSTATUSLIST,
      applyPayList: ISNOTLIST,
      customerList: [],
      rules: {
        customerId: [
          { required: true, trigger: "blur", message: "请选择客户名称" },
          { validator: validateEmpty },
        ],
        agentId: [
          { required: true, trigger: "blur", message: "请选择代理人" },
          { validator: validateEmpty },
        ],
        organizationId: [
          { required: true, trigger: "blur", message: "请选择代理商" },
          { validator: validateEmpty },
        ],
        contractNumber: [
          { required: true, trigger: "blur", message: "请选择合同编号" },
          { validator: validateEmpty },
        ],
        status: [
          { required: true, trigger: "blur", message: "请输入状态" },
          { validator: validateEmpty },
        ],
        accountTransfer: [
          { required: true, trigger: "blur", message: "请输入是否到账" },
          { validator: validateEmpty },
        ],
      },
    };
  },
  methods: {
    // 客户信息
    getCustomerSelect() {
      getCustomerListApi().then((res) => {
        this.customerList = res;
      });
    },
    // 代理人
    getSysuserSelect(val) {
      getSysuserSelectApi({ name: val }).then((res) => {
        this.sysuserSelect = res
      });
    },
    // 代理商集合
    getAgentSelect() {
      getAgentPageApi().then((res) => {
        this.agentList = res.list;
      });
    },
    customerChanged(val) {
      getCustomerInfoApi(val).then((res) => {
        this.form.customerAddress = res.customerAddress;
        this.form.customerContact = res.remark; // 客户信息页面为联系人
        this.form.customerMobile = res.customerPhone;
        this.form.customerEmail = res.customerEmail;
      });
    },
    transferChanged(val) {
      if (val == 1) {
        this.form.status = 2;
        this.form.transferDate = this.dayjs().format("YYYY-MM-DD");
      }
    },
    initDialog() {
      this.getAgentSelect();
      this.getSysuserSelect("代理人");
      if (this.dialogObj.id) {
        let json = { contractId: this.dialogObj.id };
        getContractManageApi(json).then((res) => {
          this.form.id = this.dialogObj.id;
          this.form.customerId = res.customerId;
          this.form.contractNumber = res.contractNumber;
          this.form.customerAddress = res.customerAddress;
          this.form.customerContact = res.customerContact;
          this.form.customerEmail = res.customerEmail;
          this.form.customerMobile = res.customerMobile;
          this.form.customerType = res.customerType;
          this.form.organizationId = res.organizationId;
          this.form.agentId = res.agentId;
          this.form.trusteeAddress = res.trusteeAddress;
          this.form.trusteePhone = res.trusteePhone;
          this.form.trusteeContact = res.trusteeContact;
          this.form.trusteeMail = res.trusteeMail;
          this.form.trusteeMobile = res.trusteeMobile;
          this.form.totalFee = res.totalFee;
          this.form.payType = res.payType;
          this.form.payNumber = res.payNumber;
          this.form.filePath = res.filePath;
          this.form.status = res.status;
          if (res.accountTransfer) {
            this.form.accountTransfer = parseInt(res.accountTransfer);
          } else {
            this.form.accountTransfer = "";
          }
          this.form.transferDate = res.transferDate;
          if (res.projectInfos && res.projectInfos.length > 0) {
            this.tableData = JSON.parse(JSON.stringify(res.projectInfos));
            console.log(this.tableData, 'this.tableData')
          } else {
            this.tableData = [];
          }
        });
        this.isUpdate = true;
      } else {
        this.form.id = "";
        this.form.customerId = "";
        this.form.organizationId = "";
        this.form.agentId = "";
        this.form.contractNumber = "";
        this.form.customerAddress = "";
        this.form.customerContact = "";
        this.form.customerEmail = "";
        this.form.customerMobile = "";
        this.form.customerType = "";
        this.form.trusteeAddress = "";
        this.form.trusteePhone = "";
        this.form.trusteeContact = "";
        this.form.trusteeMail = "";
        this.form.trusteeMobile = "";
        this.form.totalFee = "";
        this.form.payType = "";
        this.form.payNumber = "";
        this.form.filePath = "";
        this.form.status = "";
        this.form.accountTransfer = "";
        this.form.transferDate = "";
        this.projectInfos = [];
        this.tableData = [];
        this.isUpdate = false;
      }
    },
    handleChangeFee(total) {
      this.form.totalFee = total;
    },
    sub: _debounce(function() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.dialogObj.id) {
            this.updateSub();
          } else {
            this.addSub();
          }
        }
      });
    }),
    updateSub() {
      console.log(this.tableData,'tableData')
      for (var i = 0; i < this.tableData.length; i++) {
        if (
          !this.tableData[i].projectTypeName ||
          this.tableData[i].projectTypeName == ""
        ) {
          this.$message({
            type: "warning",
            message: "请选择服务项目中的委托项目！",
          });
          return;
        }
        if (
          !this.tableData[i].projectName ||
          this.tableData[i].projectName == ""
        ) {
          this.$message({
            type: "warning",
            message: "请选择服务项目中的项目名称！",
          });
          return;
        }
      }
      this.form.projectInfos = this.tableData;
      let json = JSON.parse(JSON.stringify(this.form));
      updateContractManageApi(json).then(() => {
        this.dialogObj.show = false;
        this.$emit("reflash");
        this.$message({
          type: "success",
          message: "修改成功！",
        });
      });
    },
    addSub() {
      for (var i = 0; i < this.tableData.length; i++) {
        if (
          !this.tableData[i].projectTypeName ||
          this.tableData[i].projectTypeName == ""
        ) {
          this.$message({
            type: "warning",
            message: "请选择服务项目中的委托项目！",
          });
          return;
        }
        if (
          !this.tableData[i].projectName ||
          this.tableData[i].projectName == ""
        ) {
          this.$message({
            type: "warning",
            message: "请选择服务项目中的项目名称！",
          });
          return;
        }
      }
      this.form.projectInfos = this.tableData;
      let json = JSON.parse(JSON.stringify(this.form));
      AddContractManageApi(json).then(() => {
        this.dialogObj.show = false;
        this.$emit("reflash");
        this.$message({
          type: "success",
          message: "添加成功！",
        });
      });
    },
    organizationChanged(val) {
      console.log(this.agentList)
      this.agentList.filter(item => {
        if(item.id === val) {
          this.form.trusteeContact = item.principal // 联系人(受托人)
          this.form.trusteeAddress = item.address // 通信地址(受托人)
          this.form.trusteePhone = item.telephone //电话号码(受托人)
          this.form.trusteeMail = item.email // 电子邮箱(受托人)
          this.form.trusteeMobile = item.phone // 移动电话(受托人)
        }
      })
    },
    handleTableDate() {},
    // Pdf上传
    handlefileSuccess(val) {
      this.form.filePath = val;
      this.form.status = 1;
    },
  },
  watch: {
    "dialogObj.show"(val) {
      if (val) {
        this.getCustomerSelect();
        this.initDialog();
      }
    },
  },
};
</script>
<style scoped lang="scss"></style>
